from timecontroller import *
import threading
from configurations.cpp import cp
import pyttsx
import time

engine = pyttsx.init()
rate = engine.getProperty("rate")
engine.setProperty("rate",rate - 100)
RECORD = 1
FREE = 2

class Speaker():
    def __init__(self):
        self.state = FREE
        self.thread = None
        self.task = cp.get("task","task")
        self.interval = None
        if(self.task == "steal"):
            self.interval = 20
        else:
            self.interval = 10
        self.weaktime = self.interval - 6

    def initialize(self):
        self.thread = threading.Thread(target=self._thread)
        logger.info("speaker start")
        self.thread.start()

    def _thread(self):
        while True:
            self.weakup()
            time.sleep(0.05)

    def currenttime_s(self):
        t = time.time()
        return int(t)

    def saysome(self,something):
        engine.say(something)
        engine.runAndWait()

    def saystart(self):
        self.saysome("start")

    def sayend(self):
        self.saysome("end")

    def weakup(self):
        timestamp = self.currenttime_s()
        time_local = time.localtime(timestamp)
        dt = time.strftime("%Y-%m-%d_%H:%M:%S",time_local)
        tail = dt.split(":")[-1].strip()
        tail = int(tail)

        tail = tail % self.interval
        if self.state == FREE:
            if tail >= self.weaktime:
                self.saystart()
                self.state = RECORD
        else:
            if tail < self.weaktime:
                self.sayend()
                self.state = FREE

speaker = Speaker()